package com.cmq.web_1.listener;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.ServletRequestEvent;
import jakarta.servlet.ServletRequestListener;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PerformanceMonitorListener implements ServletContextListener, ServletRequestListener {

    private long appStartTime; // 应用启动时间
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // 应用启动时（记录启动时间）
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        appStartTime = System.currentTimeMillis();
        ServletContext application = sce.getServletContext();
        // 初始化性能指标（存储在应用域）
        application.setAttribute("totalRequests", 0L); // 总请求数
        application.setAttribute("totalResponseTime", 0L); // 总响应时间（毫秒）
        System.out.println("【性能监控】应用启动时间：" + sdf.format(new Date(appStartTime)));
    }

    // 应用关闭时（输出运行时长）
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        long appRunTime = (System.currentTimeMillis() - appStartTime) / 1000; // 运行秒数
        System.out.println("【性能监控】应用关闭，运行时长：" + appRunTime + " 秒");
    }

    // 请求开始时（记录请求开始时间）
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        long requestStartTime = System.currentTimeMillis();
        sre.getServletRequest().setAttribute("requestStartTime", requestStartTime);
    }

    // 请求结束时（计算耗时并更新性能指标）
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        ServletContext application = sre.getServletRequest().getServletContext();
        // 获取请求开始时间
        Long requestStartTime = (Long) sre.getServletRequest().getAttribute("requestStartTime");
        if (requestStartTime == null) return;

        // 计算请求耗时
        long responseTime = System.currentTimeMillis() - requestStartTime;
        // 更新总请求数和总响应时间（同步处理）
        synchronized (this) {
            long totalRequests = (Long) application.getAttribute("totalRequests");
            long totalResponseTime = (Long) application.getAttribute("totalResponseTime");
            application.setAttribute("totalRequests", totalRequests + 1);
            application.setAttribute("totalResponseTime", totalResponseTime + responseTime);
        }

        // 计算平均响应时间
        long totalRequests = (Long) application.getAttribute("totalRequests");
        long totalResponseTime = (Long) application.getAttribute("totalResponseTime");
        double avgTime = totalRequests > 0 ? (double) totalResponseTime / totalRequests : 0;

        System.out.printf(
                "【性能监控】请求耗时：%d 毫秒 | 总请求数：%d | 平均响应时间：%.2f 毫秒%n",
                responseTime, totalRequests, avgTime
        );
    }
}